
#include "json_handler.h"
#include <rapidjson/document.h> // 依赖rapidjson库
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/writer.h>
#include "log/syslog.h"
#include <fstream>

using namespace rapidjson;
using namespace equip_system;

//
#define TAG "CModbusCofing"

std::string CModbusCofing::serialize(const ModbusConfig &data, vector<std::string> &param)
{

    return "";
}


// AJsonHandler 实现
bool CModbusCofing::read(const std::string &filename, ModbusConfig &data, string &json_string)
{
    std::ifstream file(filename);
    if (!file.is_open())
    {
        ES_LOG(TAG, LEVEL_ERROR, "Failed to open config file: %s", filename.c_str());
        return false;
    }

    // 读取文件内容到字符串
    std::string content((std::istreambuf_iterator<char>(file)),
                        std::istreambuf_iterator<char>());

    // 解析JSON
    rapidjson::Document doc;
    if (doc.Parse(content.c_str()).HasParseError())
    {
        ES_LOG(TAG, LEVEL_ERROR, "Failed to parse config file");
        return false;
    }

    // 解析Modbus配置
    if (doc.HasMember("modbus") && doc["modbus"].IsObject())
    {
        const auto &modbusObj = doc["modbus"];
        data.server_ip = JsonHandler::_getStringValue(modbusObj, "server_ip", "127.0.0.1");
        data.server_port = JsonHandler::_getIntValue(modbusObj, "server_port", 502);
        data.slave_id = JsonHandler::_getIntValue(modbusObj, "slave_id", 1);
        data.timeout = JsonHandler::_getIntValue(modbusObj, "timeout", 1000);
        data.cycle_delay = JsonHandler::_getIntValue(modbusObj, "cycle_delay", 10);
        data.retry_delay = JsonHandler::_getIntValue(modbusObj, "retry_delay", 10000);
        data.retry_count = JsonHandler::_getIntValue(modbusObj, "retry_count", 3);
    }
    else
    {
        ES_LOG(TAG, LEVEL_WARNING, "Modbus config section not found, using defaults");
    }

    return true;
}

bool CModbusCofing::write(const std::string &filename, const ModbusConfig &data)
{

    return true;
}
